# encoding:utf-8

from flask import Flask, render_template, request, redirect, url_for, session

from models import User, Question, Answer

from exts import db

from decorators import login_required

import config

app = Flask(__name__)
app.config.from_object(config)

# 初始化db
db.init_app(app)


@app.route('/')
def index():
    # 测试发现，只有完全退出浏览器，session才会失效，如果想持久化，需要设置session.permanent = True
    # user_id = session.get('user_id')
    # print(user_id)
    context = {
        'questions': Question.query.order_by('-create_time').all()
    }
    return render_template('index.html', **context)


@app.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        telephone = request.form.get('telephone')
        password = request.form.get('password')

        # 验证
        user = User.query.filter(User.telephone == telephone).first()
        if not user:
            return '未注册'
        elif password != user.password:
            return '密码错误'
        else:
            session['user_id'] = user.id
            # 默认session有效期为关闭浏览器，设置为true则保持31天
            # 如果想设置一个具体时间，则还必须加 app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7) # 配置7天有效，datetime.timedelay类型
            session.permanent = True
            return redirect(url_for('index'))


@app.route('/regist/', methods=['GET', 'POST'])
def regist():
    if request.method == 'GET':
        return render_template('regist.html')
    else:
        telephone = request.form.get('telephone')
        username = request.form.get('username')
        password1 = request.form.get('password1')
        password2 = request.form.get('password2')

        # 手机号码验证，如果被注册就不能再注册
        user = User.query.filter(User.telephone == telephone).first()
        if user:
            return '该手机号码已被注册，请更换手机号码'
        elif password1 != password2:
            return '两次密码不一致'
        else:
            user = User(telephone=telephone, username=username, password=password1)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('login'))


@app.route('/question/', methods=['GET', 'POST'])
@login_required
def question():
    if request.method == 'GET':
        return render_template('question.html')
    else:
        title = request.form.get('title')
        content = request.form.get('content')
        user_id = session.get('user_id')
        que = Question(title=title, content=content)
        user = User.query.filter(User.id == user_id).first()
        que.author = user
        db.session.add(que)
        db.session.commit()
        return redirect(url_for('index'))


@app.route('/detail/<question_id>')
def detail(question_id):
    question_model = Question.query.filter(Question.id == question_id).first()
    return render_template('detail.html', question=question_model)


@app.route('/add_answer/', methods=['POST'])
@login_required
def add_answer():
    question_id = request.form.get('question_id')
    answer_content = request.form.get('answer_content')
    answer = Answer(content=answer_content, question_id=question_id)
    ques = Question.query.filter(Question.id == question_id).first()
    answer.author_id = ques.author_id
    db.session.add(answer)
    db.session.commit()
    return redirect(url_for('detail', question_id=question_id))

if __name__ == '__main__':
    app.run()
